<template>
  <div b="1px solid #ffffff80">
    <div flex items-stretch v-for="(item, index) in modelValue" b-b="1px solid #ffffff80">
      <div flex items-center justify-center w="6" b-r="1px solid #ffffff80">{{ index + 1 }}</div>
      <div b-r="1px solid #ffffff80" flex-1> 
        <VarInput v-model:varlike="varlikes[index]"/>
      </div>
      <div b-r="1px solid #ffffff80"> 
        <ElButton size="small" type="danger" :icon="ElIconDelete" @click="deleteItem(index)"></ElButton>
      </div>
      
    </div>
    <div style="height: 1rem;"
      class="my-action" @click="listAdd"
      bg-blue flex items-center justify-center c-white>
      <ElIconPlus w3 h3 />
    </div>
  </div>
</template>

<script setup lang="ts">
import { VarInit } from "~/models/data/var_init";
import type { ListType } from '~/models/types/list_type';
import { Value } from "~/models/value/Value";
import { VarlikeAdaptor } from "~/models/varlike";

const props = defineProps<{
  type: ListType
  modelValue: any[]
}>()
const varlikes = ref([] as VarInit[])
const _varlikes_initing = ref(false)

// varlikes列表初始化

function varlikesInit() {
  // console.log('varlikesInit');
  _varlikes_initing.value = true

  const l = [] as VarInit[]
  props.modelValue.forEach(v => l.push(new VarInit(
    '',
    props.type.itemType,
    new Value(props.type.itemType, v)
  )))
  varlikes.value = l
  // console.log('varlikesInit finished');
  // console.log(varlikes.value);
  
  _varlikes_initing.value = false
}

// 监听类型变化
watch(() => props.type, varlikesInit)

// 监听数据长度变化（对具体值的外源性更改忽略）
const _modelValue = computed(() => JSON.parse(JSON.stringify(props.modelValue)))
watch(_modelValue, (val, oldVal) => {
  if (val.length !== oldVal?.length) {
    varlikesInit()
  }
}, { immediate: true, deep: true })

// varlikes列表赋值
watch(varlikes, newList => {
  if(_varlikes_initing.value) {
    // console.log('中转数据初始化未完成，跳过值上传');
    return
  }
  // console.log('list input 数据修改');
  
  emit('update:modelValue', newList.map(x => x.initial))
}, { deep: true })

const emit = defineEmits<{
  (e: 'update:modelValue', event: any[]): void,
}>()

function listAdd() {
  // console.log('list 数据添加');
  // console.log('A', props.modelValue);
  // console.log('value', props.type.itemType.default);
  props.modelValue.push(props.type.itemType.default)
  // console.log('B', props.modelValue);
  // console.log('varlikes', varlikes.value);
  emit('update:modelValue', props.modelValue)
}

function deleteItem(index: number) {
  props.modelValue.splice(index, 1)
  emit('update:modelValue', props.modelValue)
}
</script>

<style lang="scss">
.var-input-bool {
  .el-checkbox__input {
    background: #fff;
    overflow: hidden;
    border-radius: 2px;
  }
}
</style>